package org.vectrics.cms;

import java.io.File;

import org.apache.ecs.html.A;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsTagSupport;

public class ContentSummaryTag extends VectricsTagSupport {

	private static final long serialVersionUID = -4676810684125669909L;
	
	private String domainId = null;
	
	public String getDomainId() {
		return domainId;
	}

	public void setDomainId(String domainId) {
		this.domainId = domainId;
	}

	protected String makeStartTag() {
		Table table = new BorderTable();
		table.setWidth("100%");
		
		Row headerRow = table.addRow();
		headerRow.setDefaultBgImage(this.getContextPath() + "/site-graphics/tbl_hdr.gif");
		//headerRow.setDefaultCellClass("tableHdrBg");
        headerRow.setDefaultCellFontClass("tableHdrFont");
		
		
		Cell cell = headerRow.addCell();
		cell.addText(this.getPhrase("prompt.content.section"));

		cell = headerRow.addCell();
		cell.addText(this.getPhrase("prompt.content.code"));

		cell = headerRow.addCell();
		//cell.addText(this.getPhrase("prompt.content.value"));
		
		Domain domain = ThreadProperties.getDomain();
		
		String contentDirectoryName = CoreServiceLocator.getConfiguration().getDynamicContentPath(domain);
		File contentDirectory = new File(contentDirectoryName);
		if ((contentDirectory.exists()) && (contentDirectory.isDirectory())) {
			String[] subDirectoryNames = contentDirectory.list();
			for (int i = 0; i < subDirectoryNames.length; i++) {
				String subDirectoryName = subDirectoryNames[i];
				File subDir = new File(contentDirectoryName + "/" + subDirectoryName);
				if (subDir.exists() && subDir.isDirectory()) {
					String section = subDirectoryName;
					
					String[] codes = subDir.list();
					for (int j = 0; j < codes.length; j++) {
						String code = codes[j];
						//String value = FileUtil.getFileContents(subDir.getAbsolutePath() + "/" + code);
						
						//if (value.length() > 10) {
						//	value = value.substring(10) + " ...";
						//}
						Row row = table.addRow();
						row.setDefaultCellFontClass("subFont");
						cell = row.addCell();
						cell.addText(section);
						
						cell = row.addCell();
						cell.addText(code);
						
						cell = row.addCell();
						//cell.addText(value);
						A link = new A();
						link.setHref(this.getContextPath() + "/admin/content/edit.do" +
								"?section=" + section + "&code=" + code);
						link.setClass("stdLink");
						link.addElement(this.getPhrase("link.edit"));
						cell.addElement(link);
					}
				}
			}
			
		} else {
			log.debug("Directory not found");
		}
		
		
		
		return table.toString();
	}

}
